<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\PostRequest;
use App\Http\Resources\UserResource;
use App\Models\Group;
use App\Http\Resources\GroupResource;
use App\Models\Message;
use App\Models\LatestMessage;
use App\Http\Resources\MessageResource;
use App\Http\Resources\LatestMessageResource;


class PostController extends Controller
{

    public function index(PostRequest $request)
    {
        $user = $request->user();


        $friendUserIds = $user->getFriendUserIds();
        $type = $request->input('type');
        $limitMessage = Message::whereIn('from_id', $friendUserIds)->where('unique_slug', $request->input('unique_slug'))->first();
        if($limitMessage){//
            if($type=='pull'){//下拉

                $messages = Message::whereIn('from_id', $friendUserIds)->where('message_type', 'post')->where('id','>',$limitMessage->id)->latest('created_at')->paginate($request->limit??10);
            }else if ($type=='up'){//上拉
                $messages = Message::whereIn('from_id', $friendUserIds)->where('message_type', 'post')->where('id','<',$limitMessage->id)->latest('created_at')->paginate($request->limit??10);
            }
        }else{
            if($type=='pull'){//下拉 第一次默认下拉
                $messages = Message::whereIn('from_id', $friendUserIds)->where('message_type', 'post')->latest('created_at')->paginate($request->limit??10);
            }else if ($type=='up'){//上拉 这个进不来
                $messages = Message::whereIn('from_id', $friendUserIds)->where('message_type', 'post')->latest('created_at')->paginate($request->limit??10);

            }

        }

        $postsLatestMessages = LatestMessage::whereIn('group_id',$messages->pluck('to_id')->toArray())->get();//让朋友圈数量有一个初始值，接下来会动态更新
        $postsLatestMessages = LatestMessageResource::collection($postsLatestMessages);

        $messages = MessageResource::collection($messages);
        
        return response()->json(['code'=>0,'msg'=>'','data'=>['lists'=>$messages,'posts_latest_messages'=>$postsLatestMessages]]);

    }

    public function publish(PostRequest $request)
    {
        $postMessages = $request->post_messages;

        $user = $request->user();

        $data['from'] = (new UserResource($user));
        $data['from_id'] = $user->id;
        $data['sended_at'] = now()->format('Y-m-d H:i:s');

        $toGroup =  new Group();
        $toGroup->name = $user->name.'-发布的朋友圈:';//todo 找到文本
        $toGroup->avatar = $user->avatar;
        $toGroup->type = 1;
        $toGroup->extra_type = 2;
        $toGroup->user_id = $user->id;
        $toGroup->save();
        $toGroup->users()->sync([$user->id]);

        $data['unique_slug'] = $toGroup->id.'-'.now()->getTimestamp().'-'.uniqid();
        $data['to'] = (new GroupResource($toGroup));
        $data['to_id'] = $toGroup->id;
        $data['type'] = 'group';
        $data['message_type'] = 'post';
        $data['data'] = [
            'msg' => $toGroup->name,
            'content' => $toGroup->name,
            'extra' => [
                'post_messages' => $postMessages
            ]
        ];

        $selfGroup = Group::where('user_to_user', $user->id.'-'.$user->id)->first();
        if($selfGroup){//发送给自己
            event(new \App\Events\RefreshUser($selfGroup->id));
        }else{
            \Log::info($toGroup->id,[
                'action'=>'publish',
                'msg'=>'找不到自己的聊天',
                'code'=>1
            ]);
        }


        event(new \App\Events\ImSend($data));

        return response()->json(['code'=>0,'msg'=>'发布成功']);


    }

    public function joinGroup(PostRequest $request)//加入朋友圈的群聊
    {
        $user = $request->user();

        $groupId = $request->input('group_id');

        $group = Group::findOrFail($groupId);
        
        $friendUserIds = $user->getFriendUserIds();

        if(!in_array($group->user_id,$friendUserIds)){//不在我的好友列表里，不能加
            return response()->json(['code'=>1,'msg'=>'不能加入！！']);
        }

        if($group->users()->where('id',$user->id)->first()){
            return response()->json(['code'=>0,'msg'=>'您已加入过']);
        }

        $group->users()->syncWithoutDetaching([$user->id]);
        $selfGroup = $user->getSelfGroup();
        event(new \App\Events\RefreshUser($selfGroup->id));
        return response()->json(['code'=>0,'msg'=>'']);



    }
}
